package com.shlh.saas.controller;

import com.shlh.saas.common.Result;
import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.User;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.service.UserService;
import com.shlh.saas.service.UserBalanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import com.shlh.saas.service.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;


    @Autowired
    private UserBalanceService userBalanceService;


    /**
     * 获取当前登录用户信息
     * @return 用户信息
     */
    @GetMapping("/saas/info")
    public Result<User> getUserInfo() {
        try {
            log.debug("获取当前登录用户信息");
            
            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                log.warn("未登录或登录已过期");
                return Result.error("未登录或登录已过期");
            }
            
            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                log.warn("用户不存在, userId={}", userId);
                return Result.error("用户不存在");
            }
            
            log.info("获取到用户信息: userId={}, username={}", userId, user.getUsername());
            
            // 不返回密码等敏感信息
            user.setPassword(null);
            log.debug("返回用户信息成功");
            
            return Result.success(user);
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage(), e);
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前登录用户余额信息
     * @return 用户余额信息
     */
    @GetMapping("/balance/info")
    public Result<UserBalance> getUser() {
        try {
            log.debug("获取当前登录用户信息");

            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                log.warn("未登录或登录已过期");
                return Result.error("未登录或登录已过期");
            }

            // 获取用户余额信息
            UserBalance userBalance = userBalanceService.getUserBalanceById(userId);
            if (userBalance == null) {
                log.warn("用户不存在, userId={}", userId);
                return Result.error("用户不存在");
            }

            log.info("获取到用户信息: userId={}, 用户余额={}, 搜索剩余条数={}", userId, userBalance.getCashBalance(), userBalance.getViewRecordsRemaining());

            return Result.success(userBalance);
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage(), e);
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     * @param user 用户信息
     * @return 更新结果
     */
    @PutMapping("/saas/update")
    public Result<Object> updateUserInfo(@RequestBody User user) {
        try {
            log.debug("更新用户信息");
            
            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                log.warn("未登录或登录已过期");
                return Result.error("未登录或登录已过期");
            }
            
            // 获取用户信息
            User existingUser = userService.getUserById(userId);
            if (existingUser == null) {
                log.warn("用户不存在, userId={}", userId);
                return Result.error("用户不存在");
            }
            
            log.info("准备更新用户信息: userId={}, username={} -> {}", 
                    userId, existingUser.getUsername(), user.getUsername());
            
            // 设置用户ID，防止修改其他用户信息
            user.setId(existingUser.getId());
            
            // 不允许修改密码、余额、搜索次数等敏感信息
            user.setPassword(null);
            boolean success = userService.updateUser(user);
            
            if (success) {
                log.info("更新用户信息成功: userId={}", userId);
                
                // 获取最新的用户信息
                User updatedUser = userService.getUserById(existingUser.getId());
                if (updatedUser != null) {
                    // 不返回密码等敏感信息
                    updatedUser.setPassword(null);
                    log.debug("返回更新后的用户信息");
                    return Result.success(updatedUser, "更新成功");
                }
                
                return Result.success("更新成功");
            } else {
                log.warn("更新用户信息失败: userId={}", userId);
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新用户信息失败: {}", e.getMessage(), e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 购买导出次数
     * @param params 参数
     * @return 购买结果
     */
    @PostMapping("/saas/buy/export")
    public Result<Object> buyExportQuota(@RequestBody Map<String, Object> params) {
        try {
            log.debug("购买导出次数");
            
            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                log.warn("未登录或登录已过期");
                return Result.error("未登录或登录已过期");
            }
            
            // 获取购买参数
            Integer amount = Integer.parseInt(params.get("amount").toString());
            BigDecimal price = new BigDecimal(params.get("price").toString());
            BigDecimal totalPrice = new BigDecimal(params.get("totalPrice").toString());
            
            log.info("购买导出次数: userId={}, amount={}, price={}, totalPrice={}", 
                    userId, amount, price, totalPrice);
            
            // 购买导出次数
            boolean success = userService.buyExportQuota(userId, amount, totalPrice);
            
            if (success) {
                log.info("购买导出次数成功: userId={}, amount={}", userId, amount);
                
                // 获取最新的用户余额信息
                UserBalance userBalance = userBalanceService.getUserBalanceById(userId);
                
                // 构建返回结果
                Map<String, Object> data = new HashMap<>();
                data.put("balance", userBalance != null ? userBalance.getCashBalance() : new BigDecimal("0.00"));
                data.put("exportQuotaRemaining", userBalance != null ? userBalance.getExportQuotaRemaining() : 0);
                data.put("viewRecordsRemaining", userBalance != null ? userBalance.getViewRecordsRemaining() : 0);
                data.put("reverseLookupRemaining", userBalance != null ? userBalance.getReverseLookupRemaining() : 0);
                
                return Result.success(data, "购买成功");
            } else {
                log.warn("购买导出次数失败: userId={}", userId);
                return Result.error("购买失败");
            }
        } catch (Exception e) {
            log.error("购买导出次数失败: {}", e.getMessage(), e);
            return Result.error("购买失败: " + e.getMessage());
        }
    }
    
    /**
     * 购买查看更多次数
     * @param params 参数
     * @return 购买结果
     */
    @PostMapping("/saas/buy/search")
    public Result<Object> buySearchQuota(@RequestBody Map<String, Object> params) {
        try {
            log.debug("购买查看更多次数");
            
            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                log.warn("未登录或登录已过期");
                return Result.error("未登录或登录已过期");
            }
            
            // 获取购买参数
            Integer amount = Integer.parseInt(params.get("amount").toString());
            BigDecimal price = new BigDecimal(params.get("price").toString());
            BigDecimal totalPrice = new BigDecimal(params.get("totalPrice").toString());
            
            log.info("购买查看更多次数: userId={}, amount={}, price={}, totalPrice={}", 
                    userId, amount, price, totalPrice);
            
            // 购买查看更多次数
            boolean success = userService.buySearchQuota(userId, amount, totalPrice);
            
            if (success) {
                log.info("购买查看更多次数成功: userId={}, amount={}", userId, amount);
                
                // 获取最新的用户余额信息
                UserBalance userBalance = userBalanceService.getUserBalanceById(userId);
                
                // 构建返回结果
                Map<String, Object> data = new HashMap<>();
                data.put("balance", userBalance != null ? userBalance.getCashBalance() : new BigDecimal("0.00"));
                data.put("viewRecordsRemaining", userBalance != null ? userBalance.getViewRecordsRemaining() : 0);
                data.put("reverseLookupRemaining", userBalance != null ? userBalance.getReverseLookupRemaining() : 0);
                
                return Result.success(data, "购买成功");
            } else {
                log.warn("购买查看更多次数失败: userId={}", userId);
                return Result.error("购买失败");
            }
        } catch (Exception e) {
            log.error("购买查看更多次数失败: {}", e.getMessage(), e);
            return Result.error("购买失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户VIP状态
     * @return VIP状态
     */
    @GetMapping("/vip-status")
    public Result<Map<String, Object>> getVipStatus() {
        try {
            log.debug("获取用户VIP状态");
            
            // 从ThreadLocal获取用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                log.warn("未登录或登录已过期");
                return Result.error("未登录或登录已过期");
            }
            
            log.debug("从ThreadLocal获取到用户ID: {}", userId);
            
            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                log.warn("用户不存在: userId={}", userId);
                return Result.error("用户不存在");
            }
            
            log.info("获取用户VIP状态: userId={}, phone={}", userId, user.getPhone());
            
            // 使用用户ID获取用户余额信息
            UserBalance userBalance = userBalanceService.getUserBalanceById(userId);
            
            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("userId", userId);
            data.put("vipLevel", userBalance != null ? userBalance.getVipLevel() : 0);
            data.put("vipExpireDate", userBalance != null ? userBalance.getVipExpireTime() : null);
            data.put("viewRecordsRemaining", userBalance != null ? userBalance.getViewRecordsRemaining() : 0);
            data.put("emailSendRemaining", userBalance != null ? userBalance.getEmailSendRemaining() : 0);
            data.put("exportQuotaRemaining", userBalance != null ? userBalance.getExportQuotaRemaining() : 0);
            data.put("cashBalance", userBalance != null ? userBalance.getCashBalance() : new BigDecimal("0.00"));
            data.put("reverseLookupRemaining", userBalance != null ? userBalance.getReverseLookupRemaining() : 0);
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取VIP状态失败: {}", e.getMessage(), e);
            return Result.error("获取VIP状态失败: " + e.getMessage());
        }
    }
    
} 